<?php

namespace app\admin\controller\project;

use app\admin\model\User;
use app\common\common\Common;
use app\common\controller\Backend;
use app\common\helpers\CommonHelper;
use app\common\helpers\ImageUtil;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Project extends Backend
{

    /**
     * Project模型对象
     * @var \app\admin\model\project\Project
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

        $type = \app\admin\model\Type::all();
        $typeList = array_column($type,'type_name','id');
        $this->model = new \app\admin\model\project\Project;
        $areaList = array_column(Db::name('area')->field('id,name')->where('level','1')->select(),'name','id');
        $this->view->assign("projectPriorityList", $this->model->getProjectPriorityList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $typeList);
        $this->view->assign("payStatusList", Common::$pay_list);
        $this->view->assign("filingsStatusList", Common::$filings_list);
        $this->view->assign("approvalStatusList", Common::$approval_list);
        $this->view->assign("areaList", $areaList);

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['subject','type','user'])
                    ->where($where)
                    ->where(['is_del'=>0])
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','project_name','user_id','subject_id','type_id','project_no','project_leader','pocket_unit','status','is_lx','upload_time','pay_status','pay_money','zj_num','zj_num_mwh','filings_status','approval_status','area_id']);
                $row->visible(['subject']);
				$row->getRelation('subject')->visible(['subject_name']);
				$row->visible(['user']);
				$row->getRelation('user')->visible(['nickname']);
				$row->is_lx = Common::$is_lx_list[$row->is_lx] ?? '';
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 详情
     */
    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $info = $row->toArray();

        $user = User::get($info['user_id']);
        $Type = \app\admin\model\Type::get($info['type_id']);
        $Subject = \app\admin\model\Subject::get($info['subject_id']);
        $project_priority_list = Common::$project_priority_list;

        $is_lx_list = Common::$is_lx_list;
        $status_list = Common::$status_list;
        $pay_list = Common::$pay_list;
        $filings_list = Common::$filings_list;
        $approval_list = Common::$approval_list;

        $area_list = Db::name('area')->field('id,name')->where('level','1')->select();

//        $project_pics_arr =$info['project_pics'] ? explode(',',$info['project_pics']) : [];
//        if(count($project_pics_arr)>0){
//            foreach ($project_pics_arr as &$v){
//                $v = ImageUtil::handleMore($info['project_pics'])
//            }
//        }

       $Progress = collection((new \app\admin\model\project\Progress())
           ->where(['project_id'=>$ids])
           ->field('start_time,end_time,content')
           ->order('createtime')->select())
           ->toArray();
        $info2 = [
            'id'=>$info['id'],
            'User.nickname'=>$user['nickname'],
            'project_name'=>$info['project_name'],
            'project_logo'=>$info['project_logo'],
            'Subject.subject_name'=>$Subject['subject_name'],
            'Type.type_name'=>$Type['type_name'],
            'project_no'=>$info['project_no'],
            'project_leader'=>$info['project_leader'],
            'pocket_unit'=>$info['pocket_unit'],
            'project_content'=>$info['project_content'],
            'project_pics'=>ImageUtil::handleMore($info['project_pics']),
//            'project_priority'=> CommonHelper::getValue($info['project_priority'],$project_priority_list),
            'status'=>CommonHelper::getValue($info['status'],$status_list),
            'is_lx'=>CommonHelper::getValue($info['is_lx'],$is_lx_list),
            'pay_status'           => CommonHelper::getValue($info['pay_status'],$pay_list),
            'pay_money'            => $info['pay_money'],
            'zj_num'               => $info['zj_num'],
            'zj_num_mwh'               => $info['zj_num_mwh'],
            'filings_status'       => CommonHelper::getValue($info['filings_status'],$filings_list),
            'approval_status'      => CommonHelper::getValue($info['approval_status'],$approval_list),
            'area_id'              =>CommonHelper::getValue($info['area_id'],array_column($area_list,'name','id')),
            'progress_list'=>$Progress,
            'upload_time'=>$info['upload_time'],

        ];
        $this->view->assign("row", $info2);
        return $this->view->fetch();

    }


    /**
     * 指派给某个下属人员
     */
    public function edit($ids =null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $params = $this->request->post('row/a');
        if (!isset($params['head_user_id'])) {
            $userList = collection((new User())->field('IFNULL(realname,nickname)as name,id')->select())->toArray();
            $this->view->assign('userList', array_column($userList,'name','id'));
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }




}
